package club.qweqwe.listener;

import org.apache.commons.dbcp2.BasicDataSourceFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Properties;

public class DatabaseConfiglistener implements ServletContextListener {
    public static final String DATABASE_KEY = "DataSource";

    @Override
    public void contextInitialized(ServletContextEvent sce) {

        try {
            String DatabaseFileName = (String) sce.getServletContext().getInitParameter("DatabaseFileName");
            Properties properties = new Properties();
            InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(DatabaseFileName);
            properties.load(inputStream);
            String driver = (String) properties.get("driver");
            Class.forName(driver);
            DataSource dataSource = BasicDataSourceFactory.createDataSource(properties);
            sce.getServletContext().setAttribute(DATABASE_KEY, dataSource);
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
